package com.data;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import android.util.Log;

import com.bean.StuCourseBean;
import com.constant.Constant;
import com.net.ClientError;
import com.net.ClientException;
import com.net.RequestParameter;

public final class TeacherScheduleData extends BaseData
{
	private final static String TAG = "teacher_schedule_data";
	
	private ArrayList<StuCourseBean> mCourseList;
	
	@Override
	public void startParse(RequestParameter parameter) throws Exception
	{
		
		Log.i(TAG, "开始获取教师个人课表");
		
		String url = parameter.getValue("url");
		if(url == null)
			throw new NullPointerException("请求连接url为null");
		
		String referer = parameter.getValue("referer");
		if(referer == null)
			throw new NullPointerException("请求转发referer为null");
		
		
		String stream = openConnection(url, referer);
		if(stream == null)
			return;
		
		readStream(stream);
		//System.out.println(stream);
		
	} // startPase
	
	private String openConnection(final String urls, final String referer) throws Exception
	{
		URL url = new URL(urls);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setConnectTimeout(Constant.SET_CONNECTION_TIMEOUT);
		connection.setReadTimeout(Constant.SET_READ_TIMEOUT);
		connection.setUseCaches(false);
		connection.setRequestMethod("GET");
		connection.setRequestProperty("Accept", "text/html, application/xhtml+xml, */*");
		connection.setRequestProperty("Referer", referer);
		connection.setRequestProperty("Host", "jwc.xhu.edu.cn");
		connection.connect();
		
		if(connection.getResponseCode() != 200)
		{
			Log.i(TAG, "网络请求错误, 错误代码：" + connection.getResponseCode());
			
			throw new ClientException("网络请求失败", ClientError.ERROR_CONNECTION);
		}

		return getWebSource(connection.getInputStream(), "gb2312");
		
	} // openConnection
	
	private void readStream(final String stream)
	{
		Document document = Jsoup.parse(stream);
		Element table = document.getElementById("Table6");
		System.out.println(table.html().toString());
		
	} // readStream

}
